#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider
import scrapy
import json
import math
import time
import urllib.parse

from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class XinjiangKsqdShtmlPolicy(BaseTaxPolicySpider):
    name = 'xinjiang_ksqd_shtml_policy'
    
    province = '新疆维吾尔自治区'
    city: str = "喀什地区"  # 取表格
    # county: str = ""  # 取表格
    park: str = ""  # 取表格

    def start_requests(self):
        for source, county, url in [
            ['新疆维吾尔自治区喀什地区行政公署', "", "https://www.kashi.gov.cn/ksdqxzgs/c106719/zwgk_table.shtml"],
            ['新疆维吾尔自治区喀什地区行政公署', "", "https://www.kashi.gov.cn/ksdqxzgs/c106720/xzgfxwhk.shtml"],
            ['喀什市人民政府', "喀什市", "http://www.xjks.gov.cn/kss/c109279/zcxwj.shtml"],
            ['喀什市人民政府', "喀什市", "http://www.xjks.gov.cn/kss/c107455/gfxwj.shtml"],
            ['疏勒县人民政府', "疏勒县", "http://www.shule.gov.cn/slx/c107662/zwgk.shtml"],
            ['疏勒县人民政府', "疏勒县", "http://www.shule.gov.cn/slx/gfxwj/gfxwj.shtml"],
            ['疏勒县人民政府', "疏勒县", "http://www.shule.gov.cn/slx/zfwj/gfxwj.shtml"],
            ['疏勒县人民政府', "疏附县", "http://www.xjsf.gov.cn/xfx/c106779/zcxwj.shtml"],
            ['疏勒县人民政府', "疏附县", "http://www.xjsf.gov.cn/xfx/c106780/gfxwj.shtml"],
            ['伽师县人民政府', "伽师县", "http://www.xjjsx.gov.cn/jsx/c112237/zcxwj.shtml"],
            ['伽师县人民政府', "伽师县", "http://www.xjjsx.gov.cn/jsx/c118091/gfxwj.shtml"],
            ['岳普湖县人民政府', "岳普湖县", "http://www.yph.gov.cn/yphx/c108219/zcxwj.shtml"],
            ['岳普湖县人民政府', "岳普湖县", "http://www.yph.gov.cn/yphx/c108220/gfxwj.shtml"],
            ['英吉沙县人民政府', "英吉沙县", "http://www.yjs.gov.cn/yjs/c106870/gfxwj.shtml"],
            ['英吉沙县人民政府', "英吉沙县", "http://www.yjs.gov.cn/yjs/zcxwj/zcxwj.shtml"],
            ['麦盖提县人民政府', "麦盖提县", "http://www.mgt.gov.cn/mgtx/c107774/zcxwj.shtml"],
            ['莎车县人民政府', "莎车县", "http://www.shache.gov.cn/scx/zfwj/zcxwj.shtml"],
            ['莎车县人民政府', "莎车县", "http://www.shache.gov.cn/scx/c108011/gfxwj.shtml"],
            ['泽普县人民政府', "泽普县", "http://www.xjzp.gov.cn/zpx/gfxwj/gfxwj.shtml"],
            ['泽普县人民政府', "泽普县", "http://www.xjzp.gov.cn/zpx/c106967/zcxwj.shtml"],
            ['叶城县人民政府', "叶城县", "http://www.xjyc.gov.cn/ycx/c107327/zcxwj.shtml"],
            ['叶城县人民政府', "叶城县", "http://www.xjyc.gov.cn/ycx/c107329/zcxwj.shtml"],
            ['叶城县人民政府', "叶城县", "http://www.xjyc.gov.cn/ycx/c107336/gfxwj.shtml"],
            ['巴楚县人民政府', "巴楚县", "http://www.bachu.gov.cn/bcx/c107032/gfxwj.shtml"],
            ['巴楚县人民政府', "巴楚县", "http://www.bachu.gov.cn/bcx/c118094/zcxwj.shtml"],
            ['喀什库尔干县人民政府', "喀什库尔干县", "http://www.tskeg.gov.cn/tskeg/c114398/list_tj.shtml"],
        ]:
            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=self.parse_list, meta={'item': item})

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        for elem in response.xpath(
                "//div[@class='table-main' or @class='table-responsive' or @class='govnewslista2353']//td//a[contains(@href, 'htm') or @title]/ancestor::td[string-length(string(.))>=5] |"
                "//div[@class='table-main' or @class='zfxxgk_right']//dd//a[contains(@href, 'htm') or @title]/ancestor::dd[string-length(string(.))>=5] |"
                # "//table/tr/td//a[contains(@href, 'htm') or @title]/ancestor::td[string-length(string(.))>=5] |"
                "//td[@class='xx_tit']//a[contains(@href, 'htm') or @title]/ancestor::td[string-length(string(.))>=5] |"
                "//div[@class='content' or @class='zfxxgk_right']//li//a[contains(@href, 'htm') or @title]/ancestor::li[string-length(string(.))>=5] |"
                "//div[@class]/ul[@class]//li//a[contains(@href, 'htm') or @title]/ancestor::li[string-length(string(.))>=5]"):
            item = Item()
            item['source_url'] = elem.xpath(""".//a/@href""").re_first(r"""(.*)""")
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem.xpath("""string(.)""").get()
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            if '.htm' not in item['source_url'] and '.shtm' not in item['source_url']:
                continue
            print(response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            pages = response.xpath("//script").re_first(r"""createPageHTML\('page_?-?div',(\d+),""") or 0
            print(response.url, f"page: {pages}")
            for page_num in range(2, int(pages) + 1):
                url = response.url.replace(".shtml", f"_{page_num}.shtml")
                yield response.follow(url, callback=self.parse_list, meta={'item': prev_item, 'is_next': False})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get() or response.xpath("//*[@class='fbrq']/text()").get()
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl xinjiang_ksqd_shtml_policy".split())
